package com.auok.Command;


import Util.JsonUtil;
import com.auok.Entity.UserSession;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.http.ServerWebSocket;
import io.vertx.reactivex.ext.sql.SQLClient;


public class CommandHandler implements Handler<String> {

    private UserSession userSession;
    private SQLClient sqlClient;

    public CommandHandler(UserSession userSession, SQLClient sqlClient) {
        this.userSession = userSession;
        this.sqlClient = sqlClient;
    }

    @Override
    public void handle(String s) {


        ServerWebSocket webSocket = userSession.getWebSocket();

        if (webSocket == null) {
            return;
        }

        if (s.equals("HeartBeat")) {
            webSocket.writeTextMessage("HeartBeat");
        } else if (s.startsWith("{")) {

            System.out.println("接收到消息：" + s);

            Command command = JsonUtil.FromJson(s, Command.class);

            if (command.getCommandName().equals("SendToUser")) {

                var msg = JsonUtil.FromJson(command.getContent(), SendToUserCommand.class)
                        .Exec(userSession.getUser().getId());

                msg.Save(sqlClient);
            }
        }
    }


}
